package com.jeespring.elasticsearch.controller;

import com.alibaba.fastjson.JSON;
import com.jeespring.elasticsearch.dto.ResponseDTO;
import com.jeespring.elasticsearch.service.ItemService;
import com.jeespring.elasticsearch.entity.Item;
import com.jeespring.elasticsearch.dto.ItemIndexDTO;
import com.jeespring.elasticsearch.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @description SearchController
 * @author 张朝阳
 * @date 2021/9/17 17:14
 */
@RestController
@RequestMapping("/search")
public class SearchController {

    @Resource
    private ItemService itemService;

    @Autowired
    private SearchService searchService;

    @Autowired
    private ElasticsearchOperations elasticsearchOperations;

    @RequestMapping("/createItemIndex")
    public ResponseDTO createItemIndex(){
        ResponseDTO responseDTO = new ResponseDTO();
        try {
            searchService.createItemIndex();
        } catch (Exception e) {
            e.printStackTrace();
            responseDTO.setSuccess(false);
            responseDTO.setData(e.getMessage());
        }
        return responseDTO;
    }

    @RequestMapping("/createUserIndex")
    public ResponseDTO createUserIndex(){
        ResponseDTO responseDTO = new ResponseDTO();
        try {
            searchService.createUserIndex();
        } catch (Exception e) {
            e.printStackTrace();
            responseDTO.setSuccess(false);
            responseDTO.setData(e.getMessage());
        }
        return responseDTO;
    }

    @RequestMapping("/search")
    public List<Item> search(){
        Item item = new Item();
        List<Item> select = itemService.select(item);
        return select;
    }

    @PostMapping("/item")
    public String save(@RequestBody ItemIndexDTO item) {

        IndexQuery indexQuery = new IndexQueryBuilder()
                .withId(item.getId().toString())
                .withObject(item)
                .build();
        IndexCoordinates indexCoordinates = elasticsearchOperations.getIndexCoordinatesFor(item.getClass());

        String documentId = elasticsearchOperations.index(indexQuery,indexCoordinates);
        return documentId;
    }

    @GetMapping("/item/{id}")
    public ItemIndexDTO findById(@PathVariable("id")  Long id) {
        ItemIndexDTO item = elasticsearchOperations.get(id.toString(), ItemIndexDTO.class);
        return item;
    }
}
